package com.sinosoft.hydra.um.services;

import com.sinosoft.hydra.um.domain.model.DirectoryType;
import com.sinosoft.hydra.um.domain.permission.TDirectory;
import cn.com.sinux.spring.exception.ServiceException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.InputStream;
import java.util.Arrays;
import java.util.List;

/**
 * Created by Administrator on 2016/5/16.
 */
@Service
public class SystemService {

    @Autowired
    private DirectoryService directoryService;
    @Autowired
    private FileService fileService;

    /**
     * 保存logo
     *
     * @param in
     * @param fileName
     */
    @Transactional
    public void saveLogo(InputStream in, String fileName) {
        int inx = fileName.indexOf(".");
        if (inx == -1) {
            throw new ServiceException("上传文件失败，格式不匹配");
        }
        String ext = fileName.substring(inx + 1);
        if (!Arrays.asList("jpg", "png", "gif").contains(ext)) {
            throw new ServiceException("上传文件失败，格式不匹配");
        }
        String url;
        try {
            url = fileService.fileUpload(in, fileName);
        } catch (Exception e) {
            throw new ServiceException("上传文件失败,IO异常" + e.getMessage());
        }
        directoryService.addDirectory(DirectoryType.valueOf("DIRECTORY_LOGO_CONFIG"), url);
    }

    /**
     * 查询logo地址
     *
     * @return
     */
    public String queryLogoUrl() {
        List<TDirectory> directories = directoryService.findDirectories(DirectoryType.valueOf("DIRECTORY_LOGO_CONFIG"));
        return directories.isEmpty() ? null : directories.get(0).getDirValue();
    }
}
